package parallels.servertech.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import parallels.servertech.server.nio.AsyncServer;

public class ServerLoader {
	private Map<String, String> parsedArgs = new HashMap<>();
	
	private interface ServerStarter {
		void startServer(int port) throws IOException;
	}
	
	private enum ServerType implements ServerStarter {
		SYNC {
			public void startServer(int port) throws IOException {
				new Server(port).start();
			}
		}, 
		ASYNC {
			public void startServer(int port) throws IOException {
				new AsyncServer(port).start();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		ServerLoader loader = new ServerLoader();
		loader.startServer(args);
	}

	private void startServer(String[] args) throws IOException {
		parsedArgs = parseArgs(args);
		
		Integer port = getIntArg("port").orElse(8080);
		Optional<String> type = getStrArg("type");
		
		if (type.isPresent()) {
			ServerType.valueOf(type.get().toUpperCase()).startServer(port);
			return;
		}
		
		ServerType.SYNC.startServer(port);
	}

	private Optional<Integer> getIntArg(String argName) {
		String value = parsedArgs.get(argName);
		return Optional.ofNullable(value != null ? Integer.parseInt(value) : null);
	}
	
	private Optional<String> getStrArg(String argName) {
		return Optional.ofNullable(parsedArgs.get(argName));
	}

	private Map<String, String> parseArgs(String[] args) {
		Map<String, String> argsMap = new HashMap<>();
		for (String arg : args) {
			if (arg.startsWith("--") && arg.contains("=")) {
				String[] argValue = arg.split("=");
				argsMap.put(argValue[0].substring(2), argValue[1]);
			}
		}
		return argsMap;
	}
}
